package com.urbanski.clipboard.server;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.SocketException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.common.message.Message;
import com.urbanski.clipboard.server.action.message.ServerMessageHandler;


public class SocketListener implements Runnable
{
	private static final Logger LOGGER = Logger.getLogger(SocketListener.class);
	
	private ClientSocket client;
	
	public SocketListener(ClientSocket client)
	{
		this.client = client;
	}

	@Override
	public void run()
	{
		try
		{
			Object object;
			while ((object = client.getInputStream().readObject()) != null)
			{
				if (object instanceof Message)
				{
					Message message = (Message) object;
					System.out.println("Got message: " + message.getClass());
					ServerMessageHandler handler = ServerMessageHandler.getHandler(client, message);
					handler.handle(message);
				}
			}
		}
		catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
		{
			LOGGER.error("Error while handling message", e);
		}
		catch (ClassNotFoundException e)
		{
			LOGGER.error("Error reading from stream", e);
		}
		catch (SocketException e)
		{
			LOGGER.warn("Socket exception - socket may have been closed by client", e);
		}
		catch (IOException e)
		{
			LOGGER.error("Error occured while reading socket", e);
		}
		finally
		{
//			try
//			{
////				inputStream.close();
//			}
//			catch (IOException e)
//			{
//				
//			}
		}
	}

}
